# coding: UTF-8
# Filename : monitor.py
# Company : imedia
# Author : rose
# -*-coding:utf-8 -*-

#app服务器错误日志监控脚本

import codecs
import os,sys,datetime
import re
import simple_mail
import cPickle as p

#日期设定
today = str(datetime.date.today())
if len(sys.argv) >= 2:
    today = sys.argv[1]

#错误日志位置
error_log_path = '/data/log/error_log.' + str(today)

#允许错误日志条数
allowed_count = 3

#日志发送人员列表
toAdd = ['13521020805@139.com', '272200803@qq.com']

#邮件服务器设定
authInfo = {}
authInfo['server'] = 'smtp.sina.com'
authInfo['user'] = 'sys_auto_run'
authInfo['password'] = '1234567890'
fromAdd = 'sys_auto_run@sina.com'


#存储对象到文件
switchlistfile = 'switch.data'
def store_obj(obj):
    f = file(switchlistfile, 'w')
    p.dump(obj, f)
    f.close()
#获得存储文件中数据
def get_obj():
    f = file(switchlistfile)
    obj = p.load(f)
    f.close()
    return obj


#正则验证
def regex(regex, str):
    pattern = re.compile(regex)  
    match = pattern.match(str.strip())  
    if match:  
        return True
    else:
        return False

#发送错误邮件
def send_error(content):
    subject = str(today) + '--api_server_warning'
    plainText = content
    htmlText = content
    simple_mail.sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText)   

#计数器
count = 0
    
if os.path.exists(error_log_path):
    reslist =codecs.open(error_log_path, 'r', 'UTF-8')
    #邮件发送
    email_str= '<br />'
    for line in reslist :
        if regex('^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', line):
            email_str += '<br />'
            count += 1
        email_str += line
    reslist.close()
    
if count >= allowed_count:
    email_str = email_str.encode('UTF-8','strict')
    obj = get_obj()
    if obj.has_key(today):
        print obj[today]
    else:
        send_error(email_str)
        store_obj({today:count})
